package city.spring.modules.health.controller;

import city.spring.modules.health.entity.PhysicalExaminationEntity;
import city.spring.modules.health.service.PhysicalExaminationService;
import city.spring.modules.health.vo.PhysicalExaminationVO;
import city.spring.modules.oldman.service.OldmanInfoService;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：体检记录
 *
 * @author 谢金婷
 * @date 2020-08-04 14:15:52
 */
@RestController
@RequestMapping("/physical_examination")
public class PhysicalExaminationController extends ApiController {
    private final PhysicalExaminationService physicalExaminationService;
    private final OldmanInfoService oldmanInfoService;
    private final EmployeeService employeeService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<PhysicalExaminationEntity, ?>> entityOrderFields;

    public PhysicalExaminationController(PhysicalExaminationService physicalExaminationService, OldmanInfoService oldmanInfoService, EmployeeService employeeService) {
        this.physicalExaminationService = physicalExaminationService;
        this.oldmanInfoService = oldmanInfoService;
        this.employeeService = employeeService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(PhysicalExaminationEntity::getId);
        entityOrderFields.add(PhysicalExaminationEntity::getOldmanId);
        entityOrderFields.add(PhysicalExaminationEntity::getPhysicalexaminationtime);
        entityOrderFields.add(PhysicalExaminationEntity::getChecktime);
        entityOrderFields.add(PhysicalExaminationEntity::getRegisterperson);
        entityOrderFields.add(PhysicalExaminationEntity::getPhysicalexaminationhospital);
        entityOrderFields.add(PhysicalExaminationEntity::getPhysicalexaminationresult);
        entityOrderFields.add(PhysicalExaminationEntity::getPhoto);
        entityOrderFields.add(PhysicalExaminationEntity::getHeight);
        entityOrderFields.add(PhysicalExaminationEntity::getBodyweight);
        entityOrderFields.add(PhysicalExaminationEntity::getBodytemperature);
        entityOrderFields.add(PhysicalExaminationEntity::getHighpressure);
        entityOrderFields.add(PhysicalExaminationEntity::getDepression);
        entityOrderFields.add(PhysicalExaminationEntity::getPulse);
        entityOrderFields.add(PhysicalExaminationEntity::getBloodoxygensaturation);
        entityOrderFields.add(PhysicalExaminationEntity::getFastingbloodglucose);
        entityOrderFields.add(PhysicalExaminationEntity::getPostprandialbloodsugar);
        entityOrderFields.add(PhysicalExaminationEntity::getTotalcholesterol);
        entityOrderFields.add(PhysicalExaminationEntity::getHighdensitylipoproteincholesterol);
        entityOrderFields.add(PhysicalExaminationEntity::getTriglycerides);
        entityOrderFields.add(PhysicalExaminationEntity::getLowdensitylipoproteincholesterol);
        entityOrderFields.add(PhysicalExaminationEntity::getUricacid);
        entityOrderFields.add(PhysicalExaminationEntity::getQrsinterval);
        entityOrderFields.add(PhysicalExaminationEntity::getRrinterval);
        entityOrderFields.add(PhysicalExaminationEntity::getHeartrate);
        entityOrderFields.add(PhysicalExaminationEntity::getGeneralpractitionerendorsement);
        entityOrderFields.add(PhysicalExaminationEntity::getDoctoranalysisresults);
    }

    /**
     * 获取全部的 <strong>体检记录</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, PhysicalExaminationEntity entity) {
        LambdaQueryChainWrapper<PhysicalExaminationEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>体检记录</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, PhysicalExaminationVO entity, Date[] physicalexaminationtime, Date[] checktime) {
        QueryWrapper<? extends PhysicalExaminationEntity> queryWrapper = buildQuery(entity);
        if (physicalexaminationtime != null && physicalexaminationtime.length == 2) {
            queryWrapper.ge("t1.physicalexaminationtime", physicalexaminationtime[0]);
            queryWrapper.le("t1.physicalexaminationtime", physicalexaminationtime[1]);
        }
        if (checktime != null && checktime.length == 2) {
            queryWrapper.ge("t1.checktime", checktime[0]);
            queryWrapper.le("t1.checktime", checktime[1]);
        }
        return success(physicalExaminationService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
//        LambdaQueryChainWrapper<PhysicalExaminationEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<PhysicalExaminationEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (PhysicalExaminationEntity record : page.getRecords()) {
//            try {
//                OldmanInfoEntity oldmanInfoEntity = oldmanInfoService.getById(record.getOldmanId());
//                record.setOldmanName(oldmanInfoEntity.getOldmanName());
//            } catch (Exception ignore) {
//                record.setOldmanId(null);
//                record.setOldmanName("< 找不到老人 >");
//            }
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getRegisterperson());
//                record.setName(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setRegisterperson(null);
//                record.setName("< 找不到登记人 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 获取一个 <strong>体检记录</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

//        return success(physicalExaminationService.getById(id));

        QueryWrapper<PhysicalExaminationVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<PhysicalExaminationVO> records = physicalExaminationService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>体检记录</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody PhysicalExaminationEntity entity, @NonNull Principal user) {
        physicalExaminationService.savePhysicalExamination(entity, user);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>体检记录</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody PhysicalExaminationEntity entity, @NonNull Principal user) {
        entity.setId(id);
        physicalExaminationService.updatePhysicalExamination(entity, user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>体检记录</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        physicalExaminationService.deletePhysicalExamination(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>体检记录</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        physicalExaminationService.deletePhysicalExamination(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<PhysicalExaminationEntity> buildLambdaQuery(PhysicalExaminationEntity entity) {
        LambdaQueryChainWrapper<PhysicalExaminationEntity> lambdaQuery = physicalExaminationService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), PhysicalExaminationEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOldmanId()), PhysicalExaminationEntity::getOldmanId, entity.getOldmanId());
        lambdaQuery.eq(entity.getPhysicalexaminationtime() != null, PhysicalExaminationEntity::getPhysicalexaminationtime, entity.getPhysicalexaminationtime());
        lambdaQuery.eq(entity.getChecktime() != null, PhysicalExaminationEntity::getChecktime, entity.getChecktime());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRegisterperson()), PhysicalExaminationEntity::getRegisterperson, entity.getRegisterperson());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPhysicalexaminationhospital()), PhysicalExaminationEntity::getPhysicalexaminationhospital, entity.getPhysicalexaminationhospital());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPhysicalexaminationresult()), PhysicalExaminationEntity::getPhysicalexaminationresult, entity.getPhysicalexaminationresult());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getPhoto()), PhysicalExaminationEntity::getPhoto, entity.getPhoto());
        lambdaQuery.eq(entity.getHeight() != null, PhysicalExaminationEntity::getHeight, entity.getHeight());
        lambdaQuery.eq(entity.getBodyweight() != null, PhysicalExaminationEntity::getBodyweight, entity.getBodyweight());
        lambdaQuery.eq(entity.getBodytemperature() != null, PhysicalExaminationEntity::getBodytemperature, entity.getBodytemperature());
        lambdaQuery.eq(entity.getHighpressure() != null, PhysicalExaminationEntity::getHighpressure, entity.getHighpressure());
        lambdaQuery.eq(entity.getDepression() != null, PhysicalExaminationEntity::getDepression, entity.getDepression());
        lambdaQuery.eq(entity.getPulse() != null, PhysicalExaminationEntity::getPulse, entity.getPulse());
        lambdaQuery.eq(entity.getBloodoxygensaturation() != null, PhysicalExaminationEntity::getBloodoxygensaturation, entity.getBloodoxygensaturation());
        lambdaQuery.eq(entity.getFastingbloodglucose() != null, PhysicalExaminationEntity::getFastingbloodglucose, entity.getFastingbloodglucose());
        lambdaQuery.eq(entity.getPostprandialbloodsugar() != null, PhysicalExaminationEntity::getPostprandialbloodsugar, entity.getPostprandialbloodsugar());
        lambdaQuery.eq(entity.getTotalcholesterol() != null, PhysicalExaminationEntity::getTotalcholesterol, entity.getTotalcholesterol());
        lambdaQuery.eq(entity.getHighdensitylipoproteincholesterol() != null, PhysicalExaminationEntity::getHighdensitylipoproteincholesterol, entity.getHighdensitylipoproteincholesterol());
        lambdaQuery.eq(entity.getTriglycerides() != null, PhysicalExaminationEntity::getTriglycerides, entity.getTriglycerides());
        lambdaQuery.eq(entity.getLowdensitylipoproteincholesterol() != null, PhysicalExaminationEntity::getLowdensitylipoproteincholesterol, entity.getLowdensitylipoproteincholesterol());
        lambdaQuery.eq(entity.getUricacid() != null, PhysicalExaminationEntity::getUricacid, entity.getUricacid());
        lambdaQuery.eq(entity.getQrsinterval() != null, PhysicalExaminationEntity::getQrsinterval, entity.getQrsinterval());
        lambdaQuery.eq(entity.getRrinterval() != null, PhysicalExaminationEntity::getRrinterval, entity.getRrinterval());
        lambdaQuery.eq(entity.getHeartrate() != null, PhysicalExaminationEntity::getHeartrate, entity.getHeartrate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getGeneralpractitionerendorsement()), PhysicalExaminationEntity::getGeneralpractitionerendorsement, entity.getGeneralpractitionerendorsement());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDoctoranalysisresults()), PhysicalExaminationEntity::getDoctoranalysisresults, entity.getDoctoranalysisresults());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<PhysicalExaminationEntity> buildQuery(PhysicalExaminationVO entity) {
        QueryWrapper<PhysicalExaminationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.eq(StringUtils.isNotBlank(entity.getOldmanId()), "t1.oldman_id", entity.getOldmanId());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanName()), "t2.oldman_name", entity.getOldmanName());
//        wrapper.like(entity.getPhysicalexaminationtime() != null, "t1.physicalexaminationtime", entity.getPhysicalexaminationtime());
//        wrapper.like(entity.getChecktime() != null, "t1.checktime", entity.getChecktime());
        wrapper.eq(StringUtils.isNotBlank(entity.getRegisterperson()), "t1.registerperson", entity.getRegisterperson());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t3.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getPhysicalexaminationhospital()), "t1.physicalexaminationhospital", entity.getPhysicalexaminationhospital());
        wrapper.like(StringUtils.isNotBlank(entity.getPhysicalexaminationresult()), "t1.physicalexaminationresult", entity.getPhysicalexaminationresult());
        wrapper.like(StringUtils.isNotBlank(entity.getPhoto()), "t1.photo", entity.getPhoto());
        wrapper.like(entity.getHeight() != null, "t1.height", entity.getHeight());
        wrapper.like(entity.getBodyweight() != null, "t1.bodyweight", entity.getBodyweight());
        wrapper.like(entity.getBodytemperature() != null, "t1.bodytemperature", entity.getBodytemperature());
        wrapper.like(entity.getHighpressure() != null, "t1.highpressure", entity.getHighpressure());
        wrapper.like(entity.getDepression() != null, "t1.depression", entity.getDepression());
        wrapper.like(entity.getPulse() != null, "t1.pulse", entity.getPulse());
        wrapper.like(entity.getBloodoxygensaturation() != null, "t1.bloodoxygensaturation", entity.getBloodoxygensaturation());
        wrapper.like(entity.getFastingbloodglucose() != null, "t1.fastingbloodglucose", entity.getFastingbloodglucose());
        wrapper.like(entity.getPostprandialbloodsugar() != null, "t1.postprandialbloodsugar", entity.getPostprandialbloodsugar());
        wrapper.like(entity.getTotalcholesterol() != null, "t1.totalcholesterol", entity.getTotalcholesterol());
        wrapper.like(entity.getHighdensitylipoproteincholesterol() != null, "t1.highdensitylipoproteincholesterol", entity.getHighdensitylipoproteincholesterol());
        wrapper.like(entity.getTriglycerides() != null, "t1.triglycerides", entity.getTriglycerides());
        wrapper.like(entity.getLowdensitylipoproteincholesterol() != null, "t1.lowdensitylipoproteincholesterol", entity.getLowdensitylipoproteincholesterol());
        wrapper.like(entity.getUricacid() != null, "t1.uricacid", entity.getUricacid());
        wrapper.like(entity.getQrsinterval() != null, "t1.qrsinterval", entity.getQrsinterval());
        wrapper.like(entity.getRrinterval() != null, "t1.rrinterval", entity.getRrinterval());
        wrapper.like(entity.getHeartrate() != null, "t1.heartrate", entity.getHeartrate());
        wrapper.like(StringUtils.isNotBlank(entity.getGeneralpractitionerendorsement()), "t1.generalpractitionerendorsement", entity.getGeneralpractitionerendorsement());
        wrapper.like(StringUtils.isNotBlank(entity.getDoctoranalysisresults()), "t1.doctoranalysisresults", entity.getDoctoranalysisresults());
        return wrapper;
    }

}
